package com.miplus.ccrm.common;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class JSecurity {
    public static String md5Encryption(String s)
    {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] hashBytes = digest.digest(s.getBytes());
            StringBuilder hexBuilder = new StringBuilder();
            for (byte b : hashBytes) {
                String hex = Integer.toHexString((b & 0xFF) | 0x100).substring(1, 3);
                hexBuilder.append(hex);
            }
            return hexBuilder.toString();
        }
        catch (NoSuchAlgorithmException e){
            JPubUtils.PrintError("Md5Encryption",e);
        }
        return "";
    }

    public static boolean encoderMatches(String rawPassword,String encodedPassword)
    {
        String s=md5Encryption(rawPassword);
        return JPubUtils.IsEqual(s,encodedPassword);
    }

    /*
    *使用MD5加密方式，如果使用bc加密方式，需要使用SpringSecurity框架，非常繁琐，不利于扩展
    public static String bcEncryption(String s)
    {
        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
        return bc.encode(s);
    }

    public static boolean bcEncoderMatches(CharSequence rawPassword,
                                           String encodedPassword)
    {
        BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
        return bc.matches(rawPassword,encodedPassword);
    }
     */

    public static String aesEncrypt(String content, String pkey) {
        try {
            SecretKeySpec skey = new SecretKeySpec(pkey.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// "算法/加密/填充"
            cipher.init(Cipher.ENCRYPT_MODE, skey);//初始化加密器
            byte[] encrypted = cipher.doFinal(content.getBytes("UTF-8"));
            String base64EncodeStr = Base64.encodeBase64String(encrypted);
            return base64EncodeStr; // 加密后字符串
        } catch (Exception e) {
            JPubUtils.PrintError("aesEncrypt",e);
        }
        return "";
    }

    public static String aesDecode(String content, String pkey) {
        try {
            byte[] base64DecodeStr = Base64.decodeBase64(content);
            SecretKeySpec skey = new SecretKeySpec(pkey.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, skey);// 初始化解密器
            byte[] aesDecode = cipher.doFinal(base64DecodeStr);

            return new String(aesDecode, "UTF-8");
        } catch (Exception e) {
            JPubUtils.PrintError("aesDecode",e);
        }
        return "";
    }

    public static String aesDecode2(String plaintext,String secret){
        if(plaintext == null) return "";
        try{
            Cipher cipher  = Cipher.getInstance("AES");
            cipher.init(2, new SecretKeySpec(secretBytes(secret), "AES"));
            byte[] result= cipher.doFinal(Hex.decodeHex(plaintext));
            return new String(result, StandardCharsets.UTF_8);
        } catch (Exception e) {
            JPubUtils.PrintError("aesDecode2",e);
        }
        return "";
    }

    private static byte[] secretBytes(String secretKey){
        return Arrays.copyOf(DigestUtils.sha1(secretKey), 16);
    }
}
